package com.talkyun.openx.validator.impl;

import com.talkyun.openx.validator.ValidateMessage;
import com.talkyun.openx.validator.annotation.*;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ValidateHandler {
    private static Map<String, Object> ANN2IMPL = new ConcurrentHashMap<String, Object>();

    static {
        // java base validator
        ANN2IMPL.put(ObjectValidator.class.getSimpleName(), new ObjectValidatorImpl());
        ANN2IMPL.put(StringValidator.class.getSimpleName(), new StringValidatorImpl());
        ANN2IMPL.put(NumberValidator.class.getSimpleName(), new NumberValidatorImpl());
        // simple business validator
        ANN2IMPL.put(EmailValidator.class.getSimpleName(), new EmailValidatorImpl());
        ANN2IMPL.put(PhoneValidator.class.getSimpleName(), new PhoneValidatorImpl());

    }

    public ValidateMessage handle(Annotation ann, String argName, Object argVal) {
        Object impl = ANN2IMPL.get(ann.annotationType().getSimpleName());
        if (impl == null) {
            return null;
        }

        String msg = ((AbstractValidator) impl).validate(ann, argName, argVal);
        if (msg == null) {
            return null;
        }

        return new ValidateMessage(argName, msg);
    }
}